/*
Este passo a passo, foi elaborado por Roberio Rebeca https://github.com/roberiorebeca e tem o propósito de auxiliar 
a implementação do Icone da Acessibilidade no Portal Modelo.
Estes script, foi desenvolvido pelo Delmar de Lima https://github.com/delmardelima e implementado no portal modelo da
Câmara Municipal de Apui/AM https://www.apui.am.leg.br/
*/

========================================================================================================================
Copiar e Colar o texto abaixo na linha 11 do arquivo index.html, SUBSTITUINDO o texto <link rel="stylesheet" href="..... 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">


=============================================================================================
Copiar e Colar o texto abaixo na linha 17 do arquivo index.html, SUBSTITUINDO o texto </head> 

<style>
    /* Define o estilo do botão */
    .button {
        background-color: #3288F2;
        /* Cor de fundo */
        border: none;
        /* Sem borda */
        color: white;
        /* Cor do texto */
        padding: 5px;
        /* Espaçamento interno */
        text-align: center;
        /* Alinhamento do texto */
        text-decoration: none;
        /* Sem decoração de texto */
        display: inline-block;
        /* Exibição em bloco */
        font-size: 16px;
        /* Tamanho da fonte */
        margin: 4px 2px;
        /* Margem */
        cursor: pointer;
        /* Cursor */
        position: fixed;
        /* Posição fixa */
        bottom: 20px;
        /* Distância do fundo */
        right: 20px;
        /* Distância da direita */
        border-radius: 50%;
        /* Cantos arredondados */
        width: 60px;
        /* Largura */
        height: 60px;
        /* Altura */
        z-index: 1000;
    }

    /* Define o estilo do ícone */
    .fa {
        font-size: 30px;
    }


    .dropdown {
        display: none;
        position: fixed;
        bottom: 80px;
        right: 20px;
        background-color: #f1f1f1;
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 10px;
        z-index: 1000;
    }

    .dropdown a {
        display: block;
        padding: 5px 10px;
        text-decoration: none;
        color: #333;
    }

    .dropdown a:hover {
        background-color: #ddd;
    }

    #menu-title {
        background-color: #ddd;
        padding: 5px 10px;
        font-weight: bold;
    }

    #menu-options {
        display: none;
    }

    .grayscale {
        filter: grayscale(100%);
    }

    .contrast {
        filter: contrast(200%);
    }

    .negative {
        filter: invert(100%);
    }

    .light {
        background-color: #FFFFFF;
    }

    .underline-links a {
        text-decoration: underline;
    }

    .readable-font {
        font-family: Arial, sans-serif;
        font-size: 18px;
    }
    </style>
</head>

==========================================================================================================
Copiar e Colar o texto abaixo na linha 123 do arquivo index.html, DEPOIS do texto <div id="accessibility"> </div>

<!-- Define o botão -->
    
    <!-- Define o botão -->
    <button class="button" id="menu-button"><i class="fa fa-wheelchair"></i></button>

    <!-- Define o menu de opções -->
    <div class="dropdown" id="menu-options">
        <div id="menu-title">Ferramentas de acessibilidade</div>
        <a onclick="increaseText()"><i class="fas fa-text-height"></i> Aumentar texto</a>
        <a onclick="resetText()"><i class="fas fa-sync-alt"></i> Redefinir texto</a>
        <a onclick="decreaseText()"><i class="fas fa-text-height"></i> Diminuir texto</a>
        <a onclick="toggleReadableFont()"><i class="fas fa-font"></i> Fonte legível</a>
        <a onclick="tornarSiteCinza()"><i class="fas fa-barcode"></i> Escala de cinza</a>
        <a onclick="toggleContrast()"><i class="fas fa-adjust"></i> Alto Contraste</a>
        <a onclick="toggleNegative()"><i class="fas fa-eye"></i> Contraste Negativo</a>
        <a onclick="toggleLight()"><i class="fas fa-sun"></i> Fundo claro</a>
        <a onclick="toggleUnderline()"><i class="fas fa-underline"></i> Links Sublinhado</a>
        <a onclick="leitordeTela()"><i class="fas fa-volume-up"></i> Leitor de tela</a>
        <a onclick="resetSettings()"><i class="fas fa-sync-alt"></i> Redefinir</a>
    </div>

    <!-- Adiciona o script para exibir o menu de opções -->
    <script>
    // Obtém o botão e o menu de opções
    var button = document.getElementById("menu-button");
    var menu = document.getElementById("menu-options");

    // Adiciona um evento de clique ao botão
    button.addEventListener("click", function() {
        // Verifica se o menu de opções está sendo exibido
        if (menu.style.display === "none") {
            // Exibe o menu de opções
            menu.style.display = "block";
        } else {
            // Oculta o menu de opções
            menu.style.display = "none";
        }
    });

    // Tamanho da fonte padrão
    var defaultFontSize = 100;
    var fontSize = defaultFontSize;

    function increaseText() {
        fontSize += 10;
        document.body.style.fontSize = fontSize + "%";
        localStorage.setItem('fontSize', fontSize);
    }

    function resetText() {
        fontSize = defaultFontSize;
        document.body.style.fontSize = fontSize + "%";
        localStorage.setItem('fontSize', fontSize);
    }

    function decreaseText() {
        fontSize -= 10;
        document.body.style.fontSize = fontSize + "%";
        localStorage.setItem('fontSize', fontSize);
    }

    function tornarSiteCinza() {
        var element = document.body;
        element.classList.toggle("grayscale");
    }

    function toggleContrast() {
        var element = document.body;
        element.classList.toggle("contrast");
    }

    function toggleNegative() {
        var element = document.body;
        element.classList.toggle("negative");
    }

    function toggleLight() {
        var element = document.body;
        element.classList.toggle("light");
    }

    function toggleUnderline() {
        var element = document.body;
        element.classList.toggle("underline-links");
    }

    function toggleReadableFont() {
        var element = document.body;
        element.classList.toggle("readable-font");
    }

    // Função leitordeTela
    function leitordeTela() {
        // Seleciona o elemento principal
        let mainElement = document.getElementById('main-content');

        // Obtém todo o texto dentro do elemento principal
        let text = mainElement.innerText;

        // Divide o texto em palavras
        let words = text.split(' ');

        // Índice da palavra atual
        let currentWordIndex = 0;

        // Função para remover o destaque de todas as palavras
        function removeHighlight() {
            mainElement.innerHTML = mainElement.innerHTML.replace(
                /<span style="border: 1px solid black; background-color: yellow;">(.*?)<\/span>/g, '$1');
        }

        // Função para destacar uma palavra em amarelo
        function highlightWord(word) {
            let innerHTML = mainElement.innerHTML;
            let index = innerHTML.indexOf(word);
            if (index >= 0) {
                innerHTML = innerHTML.substring(0, index) +
                    "<span style='border: 1px solid black; background-color: yellow;'>" + innerHTML.substring(index,
                        index + word.length) + "</span>" + innerHTML.substring(index + word.length);
                mainElement.innerHTML = innerHTML;
            }
        }

        // Função para falar uma palavra e destacá-la
        function speakAndHighlightWord() {
            if (currentWordIndex < words.length) {
                // Remove o destaque das palavras anteriores
                removeHighlight();

                // Destaca as próximas quatro palavras
                for (let i = 0; i < 4; i++) {
                    if (currentWordIndex + i < words.length) {
                        highlightWord(words[currentWordIndex + i]);
                    }
                }

                // Cria uma nova instância de SpeechSynthesisUtterance
                let utterance = new SpeechSynthesisUtterance(words.slice(currentWordIndex, currentWordIndex + 4).join(
                    ' '));

                // Fala as palavras usando a API de síntese de fala
                window.speechSynthesis.speak(utterance);

                // Incrementa o índice da palavra atual
                currentWordIndex += 4;

                // Chama esta função novamente quando as palavras atuais terminarem de ser faladas
                utterance.onend = function(event) {
                    setTimeout(speakAndHighlightWord, 100); // Adiciona um atraso de 100ms
                };
            }
        }

        // Inicia o leitor de tela
        speakAndHighlightWord();
    }

    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function toggle(className) {
        var element = document.body;
        var isActive = element.classList.toggle(className);
        setCookie(className, isActive ? 'true' : 'false', 30);
    }

    // Função para redefinir as configurações
    function resetSettings() {
        ['grayscale', 'contrast', 'negative', 'light', 'underline-links', 'readable-font'].forEach(function(className) {
            document.body.classList.remove(className);
            setCookie(className, 'false', 30);
            fontSize = defaultFontSize;
            document.body.style.fontSize = fontSize + "%";
        });
    }

    window.onload = function() {
        ['grayscale', 'contrast', 'negative', 'light', 'underline-links', 'readable-font'].forEach(function(
            className) {
            if (getCookie(className) === 'true') {
                document.body.classList.add(className);
            }
        });
    }
    </script>
    <div vw class="enabled">
        <div vw-access-button class="active"></div>
        <div vw-plugin-wrapper>
            <div class="vw-plugin-top-wrapper"></div>
        </div>
    </div>
    <script src="https://vlibras.gov.br/app/vlibras-plugin.js"></script>
    <script>
        new window.VLibras.Widget('https://vlibras.gov.br/app');
    </script>